package cn.jtool.dig.client.comm.tunnel;

import cn.jtool.dig.common.model.Packet;
import cn.jtool.dig.common.model.PacketHeader;
import cn.jtool.dig.common.netty.ProtocolProcess;
import cn.jtool.dig.common.netty.supports.Convert;
import com.google.common.collect.Maps;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Component
@ChannelHandler.Sharable
public class TunnelDataHander extends SimpleChannelInboundHandler<byte[]> {


    private final Map<Integer, ProtocolProcess> protocolProcessMap;

    @Autowired
    public TunnelDataHander(List<ProtocolProcess> protocolProcesses) {
        this.protocolProcessMap = Maps.newHashMap();
        if(CollectionUtils.isNotEmpty(protocolProcesses)){
            protocolProcesses.forEach(protocolProcess -> protocolProcessMap.put(protocolProcess.protocolId(), protocolProcess));
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, byte[] msg) throws Exception {
        Packet packet = new Packet(msg);
        PacketHeader header = packet.getHeader();
        ProtocolProcess protocolProcess = this.protocolProcessMap.get(header.getCommand());
        if(Objects.nonNull(protocolProcess)){
            Packet outpacket = protocolProcess.process(ctx, packet);
            if(Objects.nonNull(outpacket)){
                ctx.writeAndFlush(outpacket);
            }
        }else{
            log.error("未找到对应的协议解析器: {} , {}", header.getCommand(), Convert.bytesToHexString(msg));
        }

    }
}
